import 'dart:convert';

import 'package:dio/dio.dart';

class BaseModel<T> {
  T? data;
  int? errorCode;
  String? errorMsg;

  BaseModel.fromJson(dynamic json) {
    data = json["data"];
    errorCode = json["errorCode"];
    errorMsg = json["errorMsg"];
  }
}

class ResponseInterceptor extends Interceptor {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      try {
        Map<String, dynamic> map = jsonDecode(response.data);
        var rsp = BaseModel.fromJson(map);
        if (rsp.data == null) {
          handler.reject(DioException(
              requestOptions: response.requestOptions, message: "true"));
        } else if (rsp.errorCode == -1001) {
          handler.reject(DioException(
              requestOptions: response.requestOptions, message: "需要登录"));
        } else {
          handler.next(Response(
              requestOptions: response.requestOptions, data: rsp.data));
        }
      } catch (e) {
        handler.reject(DioException(
            requestOptions: response.requestOptions, message: "$e"));
      }
    } else {
      handler.reject(DioException(requestOptions: response.requestOptions));
    }
  }
}
